#pragma once

namespace dr
{
	template<class K>
	struct BSTNode
	{
		BSTNode<K>* _left;
		BSTNode<K>* _right;

		K _key;

		BSTNode(const K& key)
			:_left(nullptr)
			, _right(nullptr)
			, _key(key)
		{}

	};

	template<class K>
	class BinarySearchTree
	{
		typedef BSTNode<K> Node;
	public:

		bool insert(const K& key)
		{
			if (_root == nullptr)
			{
				_root = BuyNode(key);
			}
			else
			{
				Node* cur = _root;
				Node* parent = cur;
				while (cur)
				{
					if (key < cur->_key)
					{
						parent = cur;
						cur = cur->_left;
					}
					else if (key > cur->_key)
					{
						parent = cur;
						cur = cur->_right;
					}
					else
					{
						return false;
					}
				}

				if (key < parent->_key)
				{
					parent->_left = BuyNode(key);
				}
				else
				{
					parent->_right = BuyNode(key);
				}
			}
			return true;
		}

		bool Find(const K& key)
		{
			Node* cur = _root;
			while (cur)
			{
				if (key == cur->_key)
				{
					return true;
				}
				else if (key < cur->_key)
				{
					cur = cur->_left;
				}
				else
				{
					cur = cur->_right;
				}
			}
			return false;
		}

		void InOrder()
		{
			_InOrder(_root);
			cout << endl;
		}

	private:
		void _InOrder(Node* root)
		{
			if (root == nullptr)
			{
				return;
			}

			_InOrder(root->_left);
			cout << root->_key << " ";
			_InOrder(root->_right);
		}

		Node* BuyNode(const K& key)
		{
			Node* ptr = new Node(key);
			return ptr;
		}

	private:
		Node* _root = nullptr;
	};
}